<?php

namespace app\common;

use app\Request;
use app\traits\Auth;
use think\Exception;
use Yansongda\Supports\Collection;

class Pay
{
	use Auth;
	/**
	 * 支付
	 * @param $pay_type *支付类型:1=微信,2=支付宝
	 * @param  $pay_amount
	 * @param  $order_no
	 * @param $mark
	 * @param $attach
	 * @return Collection
	 * @throws Exception
	 */
	public static function pay($pay_type,$pay_amount,$order_no,$mark,$attach,$openid='')
	{
		
		$config = config('pay');
		$client = request()->header('Client');
		switch ($pay_type){
			case 1:
				if ($client == 'app'){
					$result =  \Yansongda\Pay\Pay::wechat($config)->app([
						'out_trade_no' => $order_no,
						'description' => $mark,
						'amount' => [
							'total' => (int)bcmul($pay_amount, 100, 2),
							'currency' => 'CNY',
						],
						'attach' => $attach
					]);
				}elseif ($client == 'wechatmini'){
				
					$result =  \Yansongda\Pay\Pay::wechat($config)->mini([
						'out_trade_no' => $order_no,
						'description' => $mark,
						'amount' => [
							'total' => (int)bcmul($pay_amount, 100, 2),
							'currency' => 'CNY',
						],
						'payer' => [
							'openid' => $openid,
						],
						'attach' => $attach
					]);
				}else{
					throw new Exception('客户端来源错误');
				}
				break;
			case 2:
				$result =  \Yansongda\Pay\Pay::alipay($config)->app([
					'out_trade_no' => $order_no,
					'total_amount' => $pay_amount,
					'subject' => $mark,
					'passback_params' => urlencode($attach)
				])->getBody()->getContents();
	
				break;
			default:
				throw new Exception('支付类型错误');
		}
		
		return $result;
	}
	
	#退款
	public static function refund($pay_type,$pay_amount,$order_no,$refund_order_no,$reason)
	{
		$config = config('pay');
		return match ($pay_type) {
			1 => \Yansongda\Pay\Pay::wechat($config)->refund([
				'out_trade_no' => $order_no,
				'out_refund_no' => $refund_order_no,
				'amount' => [
					'refund' => (int)bcmul($pay_amount, 100, 2),
					'total' => (int)bcmul($pay_amount, 100, 2),
					'currency' => 'CNY',
				],
				'reason'=>$reason
			]),
			default => throw new Exception('支付类型错误'),
		};
	}
	
}